package com.onenine.app.view;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.activity.PostDetailActivity;
import com.onenine.app.event.CommentEvent;
import com.onenine.app.event.SpcRefreshEvent;
import com.onenine.app.model.SpcCount;
import com.onenine.app.request.ForwardRequest;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.likebutton.LikeButton;
import com.onenine.app.view.likebutton.OnLikeListener;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.AppUtils;
import com.umeng.share.UMSharer;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 创建时间：2018/7/10 0010 17:50
 * 创建人：fly
 * 功能描述：分享回复点赞条
 */
public class SpcCountBar extends LinearLayout implements View.OnClickListener
        , ShareBoardlistener, UMShareListener, OnLikeListener {

    private Context mContext;
    private TextView mTvShare, mTvPraise, mTvReply;
    private LikeButton mLikeButton;
    private SpcCount mSpcCount;
    private int mPostType, mSpanType;
    private String mPostId, mPostDesc, mPostImgUrl;
    private boolean isListShow;//是否在列表显示

    public SpcCountBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        layoutInflate();
    }

    private void layoutInflate() {
        LayoutInflater.from(mContext).inflate(R.layout
                .layout_share_praise_reply, this, true);
        setOrientation(LinearLayout.HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        mTvShare = findViewById(R.id.tv_share_count);
        mTvPraise = findViewById(R.id.tv_praise_count);
        mTvReply = findViewById(R.id.tv_reply_count);
        mLikeButton = findViewById(R.id.lb_like);
        mTvShare.setOnClickListener(this);
        mTvReply.setOnClickListener(this);
        mLikeButton.setOnLikeListener(this);
    }

    /**
     * 设置是否列表项显示
     *
     * @param listShow
     */
    public void setListShow(boolean listShow) {
        isListShow = listShow;
    }

    /**
     * 设置数据
     *
     * @param spcCount
     * @param postId
     * @param postType
     * @param postDesc
     */
    public void setData(SpcCount spcCount, String postId, int postType
            , int spanType, String postDesc, String postImage) {
        mSpcCount = spcCount;
        mPostId = postId;
        mPostDesc = postDesc;
        mPostType = postType;
        mSpanType = spanType;
        mPostImgUrl = postImage;
        mTvReply.setText(CHelper.formatPageCount(mSpcCount.getCommentNum()));
        mTvShare.setText(CHelper.formatPageCount(mSpcCount.getForwardNum()));
        bindShareCount(mSpcCount.getForwardNum());
        bindLikeCount(mSpcCount.isLikeBln(), mSpcCount.getLikeNum());
        bindCommentCount(mSpcCount.getCommentNum());
    }

    /**
     * 设置点赞控件内容
     *
     * @param isSelected
     * @param count
     */
    private void bindLikeCount(boolean isSelected, int count) {
        mTvPraise.setText(CHelper.formatPageCount(count));
        mTvPraise.setSelected(isSelected);
        mLikeButton.setLiked(isSelected);
    }

    /**
     * 设置分享控件内容
     *
     * @param count
     */
    private void bindShareCount(int count) {
        mTvShare.setText(CHelper.formatPageCount(count));
    }

    /**
     * 设置评论控件内容
     *
     * @param count
     */
    private void bindCommentCount(int count) {
        mTvReply.setText(CHelper.formatPageCount(count));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_share_count) {
            //分享
            UMSharer.getInstance().openShareBoard((Activity) mContext, this);
        } else if (v.getId() == R.id.tv_reply_count) {
            Activity activity = ActivityUtils.getTopActivity();
            if (activity != null && TextUtils.equals(activity
                    .getClass().getSimpleName(), PostDetailActivity.class.getSimpleName())) {
                //拉起评论框
                CommentEvent commentEvent = new CommentEvent();
                commentEvent.foreignPkId = mPostId;
                commentEvent.commentType = mPostType;
                commentEvent.autoInput = true;
                EventBus.getDefault().post(commentEvent);
            } else {
                //进详情
                PostDetailActivity.launchCommentActivity(getContext(), mPostId, mPostType, mSpanType);
            }
        }
    }

    @Override
    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
        String shareDesc = mPostDesc + "-" + AppUtils.getAppName();
        if (TextUtils.isEmpty(mPostImgUrl)) {
            UMSharer.getInstance().shareTextWebAction((Activity) mContext
                    , share_media, mPostDesc, shareDesc, UrlConfig.SHARE_APP_URL, this);
        } else {
            UMSharer.getInstance().shareImageTextWebAction((Activity) mContext
                    , share_media, mPostImgUrl, UrlConfig.SHARE_APP_URL, mPostDesc, shareDesc, this);
        }
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        Toasty.showNormal(R.string.share_success);
        OkRequest.getInstance().withUrl(mPostType == DataType.POST_DYNAMIC
                ? UrlConfig.DYNAMIC_FORWARD : UrlConfig.POST_FORWARD)
                .withRequest(new ForwardRequest(mPostId))
                .doRequest(SpcCountBar.class.getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            bindShareCount(mSpcCount.getForwardNum());
                            EventBus.getDefault().post(new SpcRefreshEvent(mPostId
                                    , SpcRefreshEvent.SPC_SHARE, true));
                        }
                    }
                });
    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        if (!UMSharer.getInstance().isInstall((Activity) mContext, share_media)) {
            //未安装相应手机客户端
            if (share_media == SHARE_MEDIA.WEIXIN) {
                Toasty.showNormal(R.string.wx_app_uninstall);
            } else if (share_media == SHARE_MEDIA.QQ) {
                Toasty.showNormal(R.string.qq_app_uninstall);
            }
        } else {
            Toasty.showNormal(throwable.getMessage());
        }
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        Toasty.showNormal(R.string.share_canceled);
    }

    @Override
    public void liked(LikeButton likeButton) {
        //点赞
        handleLikeStatus(true);
        CDataProcessor.doTopicPraise(mSpcCount, mPostId, CHelper.convertArticleType2PraiseType(mPostType, false));
        if (!isListShow) {
            //非列表点赞通知列表项刷新
            EventBus.getDefault().post(new SpcRefreshEvent(mPostId, SpcRefreshEvent.SPC_LIKE, true));
        }
    }

    @Override
    public void unLiked(LikeButton likeButton) {
        //取消点赞
        handleLikeStatus(false);
        CDataProcessor.doTopicPraise(mSpcCount, mPostId, CHelper.convertArticleType2PraiseType(mPostType, false));
        if (!isListShow) {
            //非列表点赞通知列表项刷新
            EventBus.getDefault().post(new SpcRefreshEvent(mPostId, SpcRefreshEvent.SPC_LIKE, false));
        }
    }

    /**
     * 点赞或取消状态
     *
     * @param add
     */
    private void handleLikeStatus(boolean add) {
        mTvPraise.setSelected(add);
        if (add) {
            mTvPraise.setText(CHelper.formatPageCount(mSpcCount.addLikeNum()));
        } else {
            mTvPraise.setText(CHelper.formatPageCount(mSpcCount.reduceLikeNum()));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SpcRefreshEvent event) {
        if (TextUtils.equals(mPostId, event.postId)) {
            //刷新列表项的操作状态
            if (event.spcType == SpcRefreshEvent.SPC_SHARE) {
                if (event.isAdd) {
                    //分享加1
                    mTvShare.setText(CHelper.formatPageCount(mSpcCount.addForwardNum()));
                }
            } else if (isListShow && event.spcType == SpcRefreshEvent.SPC_LIKE) {
                //列表项点赞加1或减1
                handleLikeStatus(event.isAdd);
                mLikeButton.setLiked(event.isAdd);
            } else if (event.spcType == SpcRefreshEvent.SPC_COMMENT) {
                //评论加1
                if (event.isAdd) {
                    //分享加1
                    mTvReply.setText(CHelper.formatPageCount(mSpcCount.addCommentNum()));
                }
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
    }

}
